﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Lyh.Core.Data;
using Lyh.Models;

namespace Lyh.Repository.Impl
{
    public class ActionRepository : BaseRepository<Action>, IActionRepository
    {
        public IList<Action> GetAllActionByAssembly()
        {
            var actions = new List<Action>();
            var types = Assembly.Load("Lyh.Controllers").GetTypes();
            foreach (var type in types)
            {
                if (type.BaseType != null && type.BaseType.Name != "BaseController") continue;
                var methods = type.GetMethods();
                foreach (var method in methods)
                {
                    if (method.ReturnType.Name != "ActionResult") continue;
                    var action = new Action
                    {
                        ActionName = method.Name,
                        ControllerName = type.Name.Replace("Controller", string.Empty)
                    };
                    var attrs = method.GetCustomAttributes(typeof (DescriptionAttribute), true);
                    if (attrs.Length > 0) action.Description = ((DescriptionAttribute) attrs[0]).Description;
                    actions.Add(action);
                }
            }
            return actions;
        }

        public IList<Action> GetActionByPage(string query, int start, int limit, out long total)
        {
            var allActions = GetAllActionByAssembly();

            total = (from a in allActions
                where a.ActionName.ToLower().Contains(query.ToLower())
                select a).Count();

            var result = (from a in allActions
                where a.ActionName.ToLower().Contains(query.ToLower())
                select a).Skip(start).Take(limit);

            return new List<Action>(result);
        }
    }
}